﻿<?php
include("../includes/db_connect.php");
include("../includes/safefunctions.php");
session_start();

if(isset($_POST["submit"])) {
	echo "<div id=\"result\">";
	$title = safety($_POST["title"]);
	$text = safety($_POST["text"]);
	$date = date("Y-m-d H:i:s");
	
	$newsQuery = mysqli_query($db, "INSERT INTO news (authorId, title, text, date) VALUES ('{$_SESSION["id"]}', '$title', '$text', '$date')");
	if($newsQuery)
		echo "Ny nyhet inlagd";
	else{
		echo "Okänt Fel";
	}
	echo "</div>";
}else{	
	$title = "";
	$toUser = "";
	if(isset($_GET["toId"])) {
		$toQuery = mysqli_query($db, "SELECT firstname, lastname, username FROM users WHERE id={$_GET["toId"]} LIMIT 1");
		if($user = $toQuery->fetch_assoc()) {
			$toUser = "{$user["username"]} ({$user["firstname"]} {$user["lastname"]})";
		}
	}
		
	if(isset($_GET["title"])) {
		$title = $_GET["title"];
	}	
	echo "<div id=\"result\">";
	echo "</div>";
		
	echo "<form class=\"mail\" method=\"GET\"><table>";
	echo "<tr><td>TITEL: </td><td><input type=\"text\" name=\"title\" value=\"$title\" maxlength=\"50\"></td></tr>";
	echo "<tr><td>TEXT: </td><td><textarea name=\"text\"></textarea maxlength=\"65535\"></td></tr>";
	echo "<tr><td><input type=\"submit\" name=\"submit\" value=\"Skicka\"></td></tr>";
	echo "</table></form>";
	
	
}

?>
<script src="script/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="script/ajaxlinks.js"></script>
<script>
var _SESSION = {};
_SESSION["currentPage"] = "addNews.php";

$('form.mail').submit(function (e) {
	e.preventDefault();
	var form = this;
	var url = "submit=get";
	url += "&title="+form["title"].value;
	url += "&text="+form["text"].value;
	
	var page = getPage(_SESSION["currentPage"], "POST", url);
	var tmpDiv = document.createElement("div");
	tmpDiv.innerHTML = page;
	document.getElementById("result").innerHTML = tmpDiv.querySelector("[id=result]").innerHTML;
	
	return false;

});
</script>